package com.zbkj.front.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbkj.common.model.Friend;
import com.zbkj.common.model.user.User;
import com.zbkj.common.result.Result;
import com.zbkj.common.result.ResultUtils;
import com.zbkj.common.session.UserSession;
import com.zbkj.common.vo.PrivateMessageVO;
import com.zbkj.service.dao.PrivateMessageDTO;
import com.zbkj.service.service.IFriendService;
import com.zbkj.service.service.IPrivateMessageService;
import com.zbkj.service.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

@Api(tags = "私聊消息")
@RestController
@RequestMapping("api/front/message/private")
@RequiredArgsConstructor
public class PrivateMessageController {

    private final IPrivateMessageService privateMessageService;
    @Autowired
    private UserService userService;
    @Autowired
    private IFriendService friendService;
    @PostMapping("/send")
    @ApiOperation(value = "发送消息", notes = "发送私聊消息")
    public Result<Long> sendMessage(@Valid @RequestBody PrivateMessageDTO vo, HttpServletRequest request) {
        User info = userService.getInfo();
        UserSession userSession = new UserSession();
        userSession.setNickName(info.getNickname());
        userSession.setUserName(info.getAccount());
        userSession.setUserId(info.getId().longValue());
        userSession.setTerminal(0);
        QueryWrapper<Friend> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(Friend::getUserId, userSession.getUserId())
                .eq(Friend::getFriendId, vo.getRecvId());
        Friend isFriend = friendService.getOne(wrapper);
        User byId1 = userService.getById(vo.getRecvId());
        if (isFriend==null){
            Friend friend = new Friend();
            friend.setUserId(vo.getRecvId());
            friend.setFriendId(info.getId().longValue());
            friend.setFriendHeadImage(info.getAvatar());
            friend.setFriendNickName(info.getNickname());
            friendService.save(friend);

            Friend friend1 = new Friend();
            friend1.setUserId(info.getId().longValue());
            friend1.setFriendId(vo.getRecvId());
            friend1.setFriendHeadImage(byId1.getAvatar());
            friend1.setFriendNickName(byId1.getNickname());
            friendService.save(friend1);
        }

        request.setAttribute("session", userSession);
        return ResultUtils.success(privateMessageService.sendMessage(vo));
    }


    @DeleteMapping("/recall/{id}")
    @ApiOperation(value = "撤回消息", notes = "撤回私聊消息")
    public Result<Long> recallMessage(@NotNull(message = "消息id不能为空") @PathVariable Long id) {
        privateMessageService.recallMessage(id);
        return ResultUtils.success();
    }


    @GetMapping("/loadMessage")
    @ApiOperation(value = "拉取消息", notes = "拉取消息,一次最多拉取100条")
    public Result<List<PrivateMessageVO>> loadMessage(@RequestParam Long minId) {
        return ResultUtils.success(privateMessageService.loadMessage(minId));
    }

    @GetMapping("/pullOfflineMessage")
    @ApiOperation(value = "拉取离线消息", notes = "拉取离线消息,消息将通过webscoket异步推送")
    public Result pullOfflineMessage(@RequestParam Long minId, HttpServletRequest request) {
        User info = userService.getInfo();
        UserSession userSession = new UserSession();
        userSession.setNickName(info.getNickname());
        userSession.setUserName(info.getAccount());
        userSession.setUserId(info.getId().longValue());
        userSession.setTerminal(0);
        request.setAttribute("session", userSession);
        privateMessageService.pullOfflineMessage(minId);
        return ResultUtils.success();
    }

    @PutMapping("/readed")
    @ApiOperation(value = "消息已读", notes = "将会话中接收的消息状态置为已读")
    public Result readedMessage(@RequestParam Long friendId) {
        privateMessageService.readedMessage(friendId);
        return ResultUtils.success();
    }

    @GetMapping("/maxReadedId")
    @ApiOperation(value = "获取最大已读消息的id",notes="获取某个会话中已读消息的最大id")
    public Result<Long> getMaxReadedId(@RequestParam Long friendId){
        return ResultUtils.success(privateMessageService.getMaxReadedId(friendId));
    }

    @GetMapping("/history")
    @ApiOperation(value = "查询聊天记录", notes = "查询聊天记录")
    public Result<List<PrivateMessageVO>> recallMessage(@NotNull(message = "好友id不能为空") @RequestParam Long friendId,
                                                        @NotNull(message = "页码不能为空") @RequestParam Long page,
                                                        @NotNull(message = "size不能为空") @RequestParam Long size) {
        return ResultUtils.success(privateMessageService.findHistoryMessage(friendId, page, size));
    }

}

